package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.MarshalException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 新增套餐
     *
     * @param setmealDTO
     * @return
     */
    @Override
    @Transactional
    public Result addSetmeal(SetmealDTO setmealDTO) {
        if (setmealDTO.getName() == null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealMapper.insertSetmeal(setmeal);
        Long setmealId = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealId);
        }
        setmealDishMapper.insertBatch(setmealDishes);
        //清理缓存数据
        String key = "setmeal_" + setmealDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }

    /**
     * 分页查询套餐
     *
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public Result page(SetmealPageQueryDTO setmealPageQueryDTO) {
        if (setmealPageQueryDTO.getPage()==null){
            setmealPageQueryDTO.setPage(1);
        }
        if (setmealPageQueryDTO.getPageSize()==null){
            setmealPageQueryDTO.setPageSize(5);
        }
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        Page<Setmeal> pageQuery = setmealMapper.pageQuery(setmealPageQueryDTO);

        long total = pageQuery.getTotal();
        List<Setmeal> setmealList = pageQuery.getResult();
        List<SetmealVO> setmealVoList = new ArrayList(setmealList.size());
        setmealList.forEach(setmeal -> {
            SetmealVO setmealVO = new SetmealVO();
            BeanUtils.copyProperties(setmeal,setmealVO);
            Category category = categoryMapper.getById(setmealVO.getCategoryId());
            setmealVO.setCategoryName(category.getName());
            setmealVoList.add(setmealVO);
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(setmealVoList);
        return Result.success(pageResult);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result delete(List<Long> ids) {
        if (ids == null || ids.size() == 0){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        for (Long id : ids) {
            Setmeal setmeal = setmealMapper.getById(id);
            if (setmeal.getStatus() == StatusConstant.ENABLE){
                return Result.error(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        ids.forEach(setmealId -> {
            setmealMapper.delete(setmealId);
            setmealDishMapper.deleteBySetmealId(setmealId);
        });
        //将所有的菜品缓存数据清理掉，所有以setmeal_开头的key
        cleanCache("setmeal_*");
        return Result.success();
    }

    /**
     * 根据id查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public Result getById(Long id) {
        if (id == null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        Setmeal setmeal = setmealMapper.getById(id);
        SetmealVO setmealVO = new SetmealVO();
        List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(id);
        BeanUtils.copyProperties(setmeal,setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);
        return Result.success(setmealVO);
    }

    /**
     * 修改套餐
     *
     * @param setmealDTO
     * @return
     */
    @Transactional
    @Override
    public Result updateSetmeal(SetmealDTO setmealDTO) {
        if (setmealDTO.getCategoryId() == null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealMapper.update(setmeal);

        setmealDishMapper.deleteBySetmealId(setmealDTO.getId());
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (setmealDishes != null && setmealDishes.size() > 0) {
            for (SetmealDish setmealDish : setmealDishes) {
                setmealDish.setSetmealId(setmealDTO.getId());
            }
        }
        setmealDishMapper.insertBatch(setmealDishes);
        //将所有的菜品缓存数据清理掉，所有以setmeal_开头的key
        cleanCache("setmeal_*");
        return Result.success();
    }

    /**
     * 修改起售和停售
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result updateSetmealStatus(Integer status, Long id) {
        if (id == null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        if (status == null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        if (status == StatusConstant.ENABLE){
            List<Dish> dishList = dishMapper.getBySetmealId(id);
            if (dishList != null && dishList.size()>0){
                dishList.forEach(dish -> {
                  if (dish.getStatus() == StatusConstant.DISABLE){
                      throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                  }
                });
            }
        }


        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setStatus(status);

        setmealMapper.update(setmeal);
        //将所有的菜品缓存数据清理掉，所有以setmeal_开头的key
        cleanCache("setmeal_*");
        return Result.success();
    }
    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        String key = "setmeal_" + setmeal.getCategoryId();
        List<Setmeal> setmealList = JSONArray.parseArray(stringRedisTemplate.opsForValue().get(key), Setmeal.class);
        if (setmealList != null && setmealList.size() > 0){
            return setmealList;
        }
        List<Setmeal> list = setmealMapper.list(setmeal);
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(list));
        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = stringRedisTemplate.keys(pattern);
        stringRedisTemplate.delete(keys);
    }

}
